import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import MainLayout from '../../components/MainLayout.js';
import '../../pages/categories/categories.css';
import networkService from '../../services/network';
import PaginationComponent from '../network/NetworkHome/components/PaginationComponent.js';

const API_BASE_URL = 'http://117.72.106.234:8080/api';

// 创建axios实例
const resourceApi = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加token
resourceApi.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

const Categories = () => {
  const [categories, setCategories] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState('');
  const [searchKeyword, setSearchKeyword] = useState('');
  const [searchTags, setSearchTags] = useState('');
  const [onlyFree, setOnlyFree] = useState(false);
  const [orderBy, setOrderBy] = useState('createdAt');
  const [orderDirection, setOrderDirection] = useState('desc');
  const [resources, setResources] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [pagination, setPagination] = useState({
    pageNum: 1,
    pageSize: 12,
    total: 0,
    totalPages: 0,
  });
  // 网络相关状态
  const [searchMode, setSearchMode] = useState('global'); // 'global' 或 'network'
  const [selectedNetworkId, setSelectedNetworkId] = useState('');
  const [userNetworks, setUserNetworks] = useState([]);
  const [isLoadingNetworks, setIsLoadingNetworks] = useState(false);
  // 新增：标记是否已执行过搜索
  const [hasSearched, setHasSearched] = useState(false);

  // 获取所有分类和用户网络，并执行初始搜索
  useEffect(() => {
    fetchCategories();
    loadUserNetworks();
    // 进入页面时执行默认的全局搜索
    performInitialSearch();
  }, []);

  // 监听分页变化，执行搜索（仅分页变化时自动搜索）
  useEffect(() => {
    // 只有在有搜索结果的情况下，分页变化才自动搜索
    if (resources.length > 0 && hasSearched) {
      searchResources();
    }
  }, [pagination.pageNum, pagination.pageSize]);

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const response = await resourceApi.get(`${API_BASE_URL}/resource/categories`);
      if (response.data.code === 200) {
        setCategories(response.data.data);
      }
    } catch (err) {
      setError('获取分类失败');
    }
  };

  // 加载用户网络
  const loadUserNetworks = async () => {
    try {
      setIsLoadingNetworks(true);
      const response = await networkService.getUserNetworks('joined');
      if (response.data.code === 200) {
        setUserNetworks(response.data.data);
      }
    } catch (error) {
    } finally {
      setIsLoadingNetworks(false);
    }
  };

  // 新增：执行初始搜索（页面加载时的默认搜索）
  const performInitialSearch = async () => {
    setLoading(true);
    try {
      // 使用默认参数进行全局搜索
      const searchParams = {
        keyword: '',
        categoryName: '',
        tags: [],
        onlyFree: false,
        orderBy: 'createdAt',
        orderDirection: 'desc',
        pageNum: 1,
        pageSize: 12,
      };

      const response = await resourceApi.post(`${API_BASE_URL}/resource/search/global`, searchParams);
      
      if (response.data.code === 200) {
        setResources(response.data.data.resources);
        setPagination({
          pageNum: 1,
          pageSize: 12,
          total: response.data.data.total,
          totalPages: response.data.data.totalPages,
        });
        setHasSearched(true);
      }
    } catch (err) {
      setError('加载资源失败');
    } finally {
      setLoading(false);
    }
  };

  // 执行资源搜索
  const searchResources = async () => {
    setLoading(true);
    try {
      // 构建搜索参数
      const searchParams = {
        keyword: searchKeyword,
        categoryName: selectedCategory,
        tags: searchTags ? searchTags.split(',').map(tag => tag.trim()) : [],
        onlyFree: onlyFree,
        orderBy: orderBy,
        orderDirection: orderDirection,
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize,
      };

      // 如果是局域网搜索，添加networkId参数
      if (searchMode === 'network' && selectedNetworkId) {
        searchParams.networkId = parseInt(selectedNetworkId);
      }

      // 根据搜索模式选择不同的API端点
      const endpoint = searchMode === 'network' 
        ? `${API_BASE_URL}/resource/search/network`
        : `${API_BASE_URL}/resource/search/global`;

      const response = await resourceApi.post(endpoint, searchParams);
      
      if (response.data.code === 200) {
        setResources(response.data.data.resources);
        setPagination({
          ...pagination,
          total: response.data.data.total,
          totalPages: response.data.data.totalPages,
        });
        setHasSearched(true);
      }
    } catch (err) {
      setError('搜索资源失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理搜索按钮点击
  const handleSearch = (e) => {
    e.preventDefault();
    // 重置页码并搜索
    setPagination({
      ...pagination,
      pageNum: 1,
    });
    searchResources();
  };

  // 处理搜索模式变化
  const handleSearchModeChange = (mode) => {
    setSearchMode(mode);
    if (mode === 'global') {
      setSelectedNetworkId('');
    }
    // 切换搜索模式时清空结果，不自动搜索
    setResources([]);
    setPagination({
      ...pagination,
      pageNum: 1,
      total: 0,
      totalPages: 0,
    });
    setHasSearched(false);
  };

  // 处理分页变化
  const handlePageChange = (page, pageSize) => {
    setPagination({
      ...pagination,
      pageNum: page,
      pageSize: pageSize || pagination.pageSize
    });
  };

  return (
    <MainLayout>
      <div className="categories-container">
        <h1 className="page-title">资源搜索</h1>
        
        {/* 搜索模式选择 */}
        <div className="search-mode-container">
          <div className="search-mode-tabs">
            <button 
              className={`mode-tab ${searchMode === 'global' ? 'active' : ''}`}
              onClick={() => handleSearchModeChange('global')}
            >
              全局搜索
            </button>
            <button 
              className={`mode-tab ${searchMode === 'network' ? 'active' : ''}`}
              onClick={() => handleSearchModeChange('network')}
            >
              局域网搜索
            </button>
          </div>
        </div>
        
        {/* 搜索表单 */}
        <div className="search-form-container">
          <form onSubmit={handleSearch} className="search-form">
            {/* 局域网选择 - 仅在局域网搜索模式下显示 */}
            {searchMode === 'network' && (
              <div className="search-row">
                <div className="search-field network-field">
                  <label>选择局域网：</label>
                  <select 
                    value={selectedNetworkId} 
                    onChange={(e) => setSelectedNetworkId(e.target.value)}
                    required={searchMode === 'network'}
                  >
                    <option value="">请选择局域网</option>
                    {userNetworks.map(network => (
                      <option key={network.networkId} value={network.networkId}>
                        {network.name}
                      </option>
                    ))}
                  </select>
                  {isLoadingNetworks && <span className="loading-text">加载中...</span>}
                </div>
              </div>
            )}
            
            <div className="search-row">
              <div className="search-field">
                <label>关键词：</label>
                <input 
                  type="text" 
                  value={searchKeyword} 
                  onChange={(e) => setSearchKeyword(e.target.value)}
                  placeholder="输入关键词搜索"
                />
              </div>
              
              <div className="search-field">
                <label>分类：</label>
                <select 
                  value={selectedCategory} 
                  onChange={(e) => setSelectedCategory(e.target.value)}
                >
                  <option value="">全部分类</option>
                  {categories.map(category => (
                    <option key={category.categoryId} value={category.name}>
                      {category.icon} {category.name}
                    </option>
                  ))}
                </select>
              </div>
            </div>
            
            <div className="search-row">
              <div className="search-field">
                <label>标签：</label>
                <input 
                  type="text" 
                  value={searchTags} 
                  onChange={(e) => setSearchTags(e.target.value)}
                  placeholder="多个标签用逗号分隔"
                />
              </div>
              
              <div className="search-field checkbox-field">
                <label>
                  <input 
                    type="checkbox" 
                    checked={onlyFree} 
                    onChange={(e) => setOnlyFree(e.target.checked)}
                  />
                  仅显示免费资源
                </label>
              </div>
            </div>
            
            <div className="search-row">
              <div className="search-field">
                <label>排序方式：</label>
                <select 
                  value={orderBy} 
                  onChange={(e) => setOrderBy(e.target.value)}
                >
                  <option value="createdAt">创建时间</option>
                  <option value="likesCount">点赞数</option>
                  <option value="torrentDownloadsCount">下载次数</option>
                </select>
              </div>
              
              <div className="search-field">
                <label>排序方向：</label>
                <select 
                  value={orderDirection} 
                  onChange={(e) => setOrderDirection(e.target.value)}
                >
                  <option value="desc">降序</option>
                  <option value="asc">升序</option>
                </select>
              </div>
            </div>
            
            <div className="search-actions">
              <button 
                type="submit" 
                className="search-btn"
                disabled={searchMode === 'network' && !selectedNetworkId}
              >
                搜索
              </button>
              <button 
                type="button" 
                className="reset-btn"
                onClick={() => {
                  setSearchKeyword('');
                  setSelectedCategory('');
                  setSearchTags('');
                  setOnlyFree(false);
                  setOrderBy('createdAt');
                  setOrderDirection('desc');
                  if (searchMode === 'network') {
                    setSelectedNetworkId('');
                  }
                }}
              >
                重置
              </button>
            </div>
          </form>
        </div>
        
        {/* 分类筛选器 */}
        <div className="category-filter">
          <h3>快速分类筛选：</h3>
          <div className="category-buttons">
            <button 
              className={selectedCategory === '' ? 'active' : ''} 
              onClick={() => setSelectedCategory('')}
            >
              全部
            </button>
            {categories.map(category => (
              <button
                key={category.categoryId}
                className={selectedCategory === category.name ? 'active' : ''}
                onClick={() => setSelectedCategory(category.name)}
              >
                {category.icon} {category.name}
              </button>
            ))}
          </div>
        </div>
        
        {/* 搜索结果提示 - 只在局域网搜索模式且有搜索结果时显示 */}
        {searchMode === 'network' && selectedNetworkId && hasSearched && resources.length > 0 && (
          <div className="search-info">
            <p>正在搜索局域网: {userNetworks.find(n => n.networkId === parseInt(selectedNetworkId))?.name}</p>
          </div>
        )}
        
        {/* 资源列表 */}
        {loading ? (
          <div className="loading-container">
            <div className="loading-spinner"></div>
            <p>加载中...</p>
          </div>
        ) : error ? (
          <div className="error-message">{error}</div>
        ) : (
          <div>
            <div className="resources-grid">
              {resources.length > 0 ? (
                resources.map(resource => (
                  <div key={resource.resourceId} className="resource-card">
                    <div className="resource-image">
                      <img 
                        src={resource.coverUrl || '/default-cover.jpg'} 
                        alt={resource.title}
                        onError={(e) => { e.target.src = '/default-cover.jpg' }}
                      />
                      {resource.isFree && <span className="free-badge">免费</span>}
                      {resource.isAvailable && <span className="available-badge">可用</span>}
                    </div>
                    <div className="resource-info">
                      <h3 className="resource-title" title={resource.title}>
                        {resource.title.length > 20 ? resource.title.substring(0, 20) + '...' : resource.title}
                      </h3>
                      <div className="resource-meta">
                        <span className="category-label">{resource.categoryId}</span>
                        <div className="resource-stats">
                          <span><span className="stat-icon">👍</span> {resource.likesCount}</span>
                          <span><span className="stat-icon">⬇️</span> {resource.torrentDownloadsCount}</span>
                        </div>
                      </div>
                      <div className="resource-tags">
                        {resource.tags && resource.tags.slice(0, 3).map((tag, index) => (
                          <span key={index} className="tag">{tag}</span>
                        ))}
                        {resource.tags && resource.tags.length > 3 && <span className="tag more-tag">...</span>}
                      </div>
                    </div>
                    <div className="resource-actions">
                      <Link to={`/resource/detail/${resource.resourceId}`} className="btn view-btn">查看详情</Link>
                    </div>
                  </div>
                ))
              ) : hasSearched ? (
                <div className="no-resources">
                  <div className="search-hint-icon">😔</div>
                  <p>未找到符合条件的资源</p>
                  <p className="hint-subtitle">请尝试调整搜索条件或查看其他分类</p>
                </div>
              ) : (
                <div className="no-resources">
                  <div className="search-hint-icon">🔍</div>
                  <p>请设置搜索条件并点击"搜索"按钮开始查找资源</p>
                  <p className="hint-subtitle">您可以通过关键词、分类、标签等条件来筛选资源</p>
                </div>
              )}
            </div>
            
            {/* 分页 */}
            {resources.length > 0 && (
              <div className="pagination-container">
                <PaginationComponent
                  current={pagination.pageNum}
                  pageSize={pagination.pageSize}
                  total={pagination.total}
                  onChange={handlePageChange}
                />
              </div>
            )}
          </div>
        )}
      </div>
    </MainLayout>
  );
};

export default Categories;